﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SosaAnalysisModule.Data;
using System.IO;

namespace SosaAnalysisModule.Modules
{
    public class DirectoryReader
    {

        /// <summary>
        /// takes a directory and puts all sosa files in that directory into a list
        /// </summary>
        /// <param name="directory">a directory containing sosa files</param>
        /// <returns>a list of SosaData objects</returns>
        public static SosaData[] GetSosaData(string directory)
        {
            List<SosaData> SosaFiles = new List<SosaData>();

            //get all csv files in the directory
            string[] filePaths;
            try
            {
                filePaths = Directory.GetFiles(directory, "*.csv", SearchOption.AllDirectories);
            }
            catch (Exception e)
            {
                return SosaFiles.ToArray();
            }
            

            for (int i = 0; i < filePaths.Length; i++)
            {
                //check to see if the csv is a sosa file
                List<string[]> parsedCSV = SOSAFileReader.ParseCSV(filePaths[i]);
                bool isSosa = true;
                //check for a few fields to see if its a sosa csv
                if (!parsedCSV.ElementAt(0)[0].Equals("Experiment:")) isSosa = false;
                if (!parsedCSV.ElementAt(1)[0].Equals("Version:")) isSosa = false;
                if (!parsedCSV.ElementAt(2)[0].Equals("Subject:")) isSosa = false;
                if (!parsedCSV.ElementAt(3)[0].Equals("Date:")) isSosa = false;
                
                //if its create SosaData to the list
                if (isSosa)
                    SosaFiles.Add(SOSAFileReader.CreateSosaData(parsedCSV));
            }

            return SosaFiles.ToArray();
        }
    }
}
